package com.tepth.maintenancesystem.untils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.tepth.maintenancesystem.bean.MaintainRefer;
import com.tepth.maintenancesystem.bean.User;
import com.tepth.maintenancesystem.bean.VersionUpdate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by LHQ on 2016/11/18.
 */

public class Untils {

    private static final String FILENAME = "tepthUserInfo.json"; // 用户保存文件名
    private static final String FILEVERSION = "userversion.json";//用户版本信息
    private static final String FILEMAINTAINREFER = "usermaintainrefer.json";//用户保养信息对照表
    private static final String TAG = "Utils";

    /* 保存用户登录信息列表 */
    public static void saveUserList(Context context, ArrayList<User> users)
            throws Exception {
        /* 保存 */
        Writer writer = null;
        OutputStream out = null;
        JSONArray array = new JSONArray();
        for (User user : users) {
            array.put(user.toJSON());
        }
        try {
            out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); // 覆盖
            writer = new OutputStreamWriter(out);
            Log.i(TAG, "json的值:" + array.toString());
            writer.write(array.toString());
        } finally {
            if (writer != null)
                writer.close();
        }

    }

    /* 获取用户登录信息列表 */
    public static ArrayList<User> getUserList(Context context) {
		/* 加载 */
        FileInputStream in = null;
        ArrayList<User> users = new ArrayList<User>();
        try {

            in = context.openFileInput(FILENAME);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuilder jsonString = new StringBuilder();
            JSONArray jsonArray = new JSONArray();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            Log.i(TAG, jsonString.toString());
            jsonArray = (JSONArray) new JSONTokener(jsonString.toString())
                    .nextValue(); // 把字符串转换成JSONArray对象
            for (int i = 0; i < jsonArray.length(); i++) {
                User user = new User(jsonArray.getJSONObject(i));
                users.add(user);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return users;
    }

    public static int getColor(Context context, int colorId) {
        return ContextCompat.getColor(context, colorId);
    }

    public static Drawable getDrawable(Context context, int drawableId) {
        return ContextCompat.getDrawable(context, drawableId);
    }

    /**
     * 设置当前用户在保存的用户组里下标
     *
     * @param context
     * @param index
     */
    public static void setUserIndex(Context context, int index) {
        SharedPreferences preferences = context.getSharedPreferences("UserIndex",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("UserIndex", index);
        editor.commit();
    }

    /**
     * 获取当前用户在保存的用户组里下标
     *
     * @param context
     * @return
     */
    public static int getUserIndex(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("UserIndex",
                Context.MODE_PRIVATE);
        return preferences.getInt("UserIndex", 0);
    }

    /**
     * 设置当前用户在保存的用户组里下标
     *
     * @param context
     * @param mac
     */
    public static void setNFCMAC(Context context, String mac) {
        SharedPreferences preferences = context.getSharedPreferences("NFCMAC",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("NFCMAC", mac);
        editor.commit();
    }

    /**
     * 获取当前用户在保存的用户组里下标
     *
     * @param context
     * @return
     */
    public static String getNFCMAC(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("NFCMAC",
                Context.MODE_PRIVATE);
        return preferences.getString("NFCMAC", "");
    }

    /**
     * 保存更新的信息
     *
     * @param context
     * @param update
     * @throws Exception
     */
    public static void saveVersionUpdate(Context context, VersionUpdate update) throws Exception {
        Writer writer = null;
        OutputStream out = null;
        JSONObject object = update.toJSON();
        try {
            out = context.openFileOutput(FILEVERSION, Context.MODE_PRIVATE); // 覆盖
            writer = new OutputStreamWriter(out);
            writer.write(object.toString());
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    /**
     * 获取更新信息
     *
     * @param context
     * @return
     */
    public static VersionUpdate getVersionUpdate(Context context) {
        /* 加载 */
        FileInputStream in = null;
        VersionUpdate versionUpdate = null;
        try {
            in = context.openFileInput(FILEVERSION);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuilder jsonString = new StringBuilder();
            JSONObject jsonObject = new JSONObject();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            jsonObject = (JSONObject) new JSONTokener(jsonString.toString())
                    .nextValue(); // 把字符串转换成JSONArray对象
            versionUpdate = new VersionUpdate(jsonObject);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return versionUpdate;
    }

    /**
     * 保存保养信息对照表
     *
     * @param context
     * @param array
     * @throws Exception
     */
    public static void saveMaintianRefer(Context context, JSONArray array) throws Exception {
        Writer writer = null;
        OutputStream out = null;
        try {
            out = context.openFileOutput(FILEMAINTAINREFER, Context.MODE_PRIVATE); // 覆盖
            writer = new OutputStreamWriter(out);
            writer.write(array.toString());
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    /**
     * 获取更新信息
     *
     * @param context
     * @return
     */
    public static List<MaintainRefer> getMaintianRefer(Context context) {
        /* 加载 */
        FileInputStream in = null;
        JSONArray array = null;
        List<MaintainRefer> refers = new ArrayList<>();
        try {
            in = context.openFileInput(FILEMAINTAINREFER);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuilder jsonString = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            array = (JSONArray) new JSONTokener(jsonString.toString())
                    .nextValue(); // 把字符串转换成JSONArray对象
            for (int i = 0; i < array.length(); i++) {
                refers.add(new MaintainRefer(array.getJSONObject(i)));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return refers;
    }

    /**
     * 获取当前应用版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        try {
            String versionName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
//            int versionCode = this.getPackageManager()
//                    .getPackageInfo(context.getPackageName(), 0).versionCode;
            return versionName;
        } catch (Exception e) {
        }
        return "5.1";
    }


    public static String getLastString(String code) {
        if (code == null || code.equals("null"))
            return "null";
        else
            return code.substring(code.length() - 1, code.length());

    }
}
